<?php

namespace App\Console\Commands;

use App\Models\InnerCar;
use App\Models\ParkRecord;
use App\Models\ParkInfo;
use Carbon\Carbon;
use Illuminate\Console\Command;

class InnerParkCollection extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'inner-park:collection';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '场内车汇聚';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $cars = ParkRecord::leaveFlow();

        $now = Carbon::now();
        $hour = Carbon::create($now->year, $now->month, $now->day, $now->hour);

        $cars->map(function ($item) use ($hour) {
            $parks[] = $item->park_code;

            $park = ParkInfo::where("park_code", $item->park_code)
                        ->select("space_total", 'space_empty',"park_code")
                        ->first();
            $inner_park = $park->space_total - $park->space_empty;

            InnerCar::updateOrCreate(
                [
                'park_code' => $item->park_code,
                'hour' => $hour
                ],
                [
                    'inner_park' => $inner_park > 0 ? $inner_park : 0
                ]
            );

        });
        // $cars->map(function ($item) use ($hour) {
        //     InnerCar::updateOrCreate(
        //         [
        //         'park_code' => $item->park_code,
        //         'hour' => $hour
        //         ],
        //         ['inner_park' => $item->inner_park]
        //     );
        // });

        // $park_res = ParkInfo::whereIn("park_code", $parks)
        //                 ->select("space_total", 'space_empty',"park_code")
        //                 ->get();

        // // $park_total = [];
        // // $park_space = [];
        // foreach ($park_res as $val) {
        //     // $park_total[$val->park_code] = $val->space_total;
        //     // $park_space[$val->park_code] = $val->space_empty;

        //     $inner_park = $val->space_total - $val->space_empty;
        //     $inner_park = $inner_park > 0 ? $inner_park : 0;

        //     InnerCar::updateOrCreate(
        //         [
        //         'park_code' => $val->park_code,
        //         'hour' => $hour
        //         ],
        //         ['inner_park' => $inner_park]
        //     );

        // }

        $this->info('场内车量汇聚成功');
    }
}
